package org.geektimes.web.validator.bean.validation;

import javax.annotation.PostConstruct;
import javax.validation.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DelegatingValidator {

    private Validator validator;

    @PostConstruct
    public void init() {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        this.validator = factory.getValidator();
    }

    public <T> Map<String,String> validate(T object, Class<?>... groups) {
        Map<String,String> error = new HashMap<>();
        Set<ConstraintViolation<T>> validate = validator.validate(object, groups);
        for (ConstraintViolation<T> tConstraintViolation : validate) {
            Path propertyPath = tConstraintViolation.getPropertyPath();
            String message = tConstraintViolation.getMessage();
            error.put(propertyPath.toString(),message);
        }
        return error;
    }
}
